#include "AEncoderManager.h"

namespace Media{
    AEncoderManager::Ptr AEncoderManager::Instance(){
        static auto ptr = std::make_shared<AEncoderManager>();
        return ptr;
    }
    AEncoderManager::AEncoderManager(){
        for(EncChannel i = 0; i< MAX_ENCODER_NUM; i++){
            m_encoders[i] = false;
        }
    }
    AEncoderManager::~AEncoderManager(){

    }
    bool AEncoderManager::CreateEncoder(AEncoder::Ptr& ptr, const AEncoderConfig& config){
        std::lock_guard<std::recursive_mutex> guard(m_mux);
        EncChannel chan;
        if(getAvailableChannel(chan)){
            ptr = std::make_shared<AEncoder>(chan, config);
            m_encoders[chan] = true;
            return true;
        }
        
        return false;
    }
    bool AEncoderManager::ReleaseEncoder(const AEncoder::Ptr& ptr){
        std::lock_guard<std::recursive_mutex> guard(m_mux);
        if(ptr){
            ptr->Stop();
            EncChannel chan = ptr->GetChannel();
            if(m_encoders.find(chan) != m_encoders.end()){
                m_encoders[chan] = false;
            }
        }
        return true;
    }

    bool AEncoderManager::getAvailableChannel(EncChannel& channel){
        std::lock_guard<std::recursive_mutex> guard(m_mux);
        for(auto [key, val]: m_encoders){
            if(!val){
                channel = key;
                return true;
            }
        }
        return false;
    }

}